<template>
	<view>
		<form>

			<view class="cu-form-group margin-top">
				<view class="title">姓名</view>
				<input placeholder="请输入姓名" name="input" v-model='userInfo.name'></input>
			</view>
			<view class="cu-form-group" @tap="showModal" data-target="bottomModal">
				<view class="title">部门</view>
				<input placeholder="请选择部门" name="input" v-model='userInfo.department' disabled=true></input>
			</view>
			<view class="cu-form-group">
				<view class="title">手机号码</view>
				<text>{{userInfo.mobile}}</text>
				<view class="cu-capsule radius">
					<button type="default" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" size="mini">获取微信绑定手机号</button>
				</view>
			</view>
			<view class="cu-form-group">
				<view class="title">工号</view>
				<input placeholder="4位数工号, 如0001" name="input" v-model='userInfo.indexNum'></input>
			</view>
		</form>
		<button class="button-box bg-blue" @click="submit">提交</button>
		<!-- 部门弹窗 -->
		<view class="cu-modal bottom-modal" :class="modalName=='bottomModal'?'show':''">
			<view class="cu-dialog bg-white">
				<view class="cu-bar bg-white">
					<view class="action text-blue" @tap="hideModal">取消</view>
					<view class="action text-green" @click="saveChoose">确定</view>
				</view>
				<picker-view indicator-style="height: 50px;" :value="department_index" @change="PickerChange" class="picker-view">
					<picker-view-column>
						<view class="item" v-for="(item,index) in departmentInfo_1" :key="index">{{item.name}}</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in departmentInfo_2" :key="index">{{item.name}}</view>
					</picker-view-column>
				</picker-view>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	const db = uniCloud.database();
	const _ = db.command;

	export default {
		data() {
			return {
				userInfo: null,
				department_index: [0, 0],
				modalName:null,
				departmentInfo_1: [], // 一级部门
				departmentInfo_2: [] // 二级部门
			};
		},

		onShow() {
			this.userInfo = app.globalData.userInfo;
			db.collection('opendb-department').where({
				parent_id: _.eq('-1')
			}).field('_id, name').get().then(res => {
				this.departmentInfo_1 = res.result.data;
				db.collection('opendb-department').where({
					parent_id: this.departmentInfo_1[0]._id
				}).field('_id, name').get().then(res => {
					this.departmentInfo_2 = res.result.data;
				});
			});

		},

		methods: {
			// 部门选择器
			PickerChange(e) {
				const val = e.detail.value;
				this.department_index = val;
				db.collection('opendb-department').where({
					parent_id: this.departmentInfo_1[val[0]]._id
				}).field('_id, name').get().then(res => {
					this.departmentInfo_2 = res.result.data;
				});
			},
			
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			
			hideModal(e) {
				this.modalName = null
			},
			
			saveChoose(e) {
				// 只显示二级部门
				const department = this.departmentInfo_2[this.department_index[1]];
				this.userInfo.department = department.name;
				this.userInfo.department_id = [department._id];
				this.modalName = null;
			},

			// 提交
			submit: function(e) {
				if (this.userInfo.name && this.userInfo.department && this.userInfo.mobile.length == 11 && this.userInfo.indexNum.length ==
					4) {
					// 更新数据库中的用户信息
					db.collection('uni-id-users')
						.doc(app.globalData.uid).update({
							name: this.userInfo.name,
							department_id: this.userInfo.department_id,
							mobile: this.userInfo.mobile,
							department: this.userInfo.department,
							indexNum: this.userInfo.indexNum
						}).then((res) => {
							app.globalData.userInfo = this.userInfo;
							uni.showToast({
								title: "更新信息成功"
							})
							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								})
							}, 1500)
						})
				} else {
					uni.showToast({
						icon: "none",
						title: "请填写完整信息"
					})
				}

			},

			/* 
			 * 
			 * 获取用户手机号
			 * 
			 */
			getPhoneNumber: function(e) {
				var that = this;
				if (e.detail.errMsg == "getPhoneNumber:fail user deny") { //用户决绝授权  

					//拒绝授权后弹出一些提示  

				} else { //允许授权  
					uni.getStorage({key: "sessionKey"}).then(res => {
						uniCloud.callFunction({
							name: "WXDataCrypt",
							data: {
								encryptedData: e.detail.encryptedData, //加密的用户信息  
								iv: e.detail.iv, //加密算法的初始向量
								sessionKey: res[1].data
							}
						}).then(res => {
							that.userInfo["mobile"] = res.result.phoneNumber;
							uni.showToast({
								title: "获取成功"
							})
						}).catch(err => {
							console.log(err)
							uni.showToast({
								title: "获取失败，请稍后重试"
							})
						})
					})
				}
			},

			getWeixinCode: function() {
				return new Promise((resolve, reject) => {
					// #ifdef APP-PLUS
					weixinAuthService.authorize(function(res) {
						resolve(res.code)
					}, function(err) {
						console.log(err)
						reject(new Error('微信登录失败'))
					});
					// #endif
					// #ifdef MP-WEIXIN
					uni.login({
						provider: 'weixin',
						success(res) {
							resolve(res.code)
						},
						fail(err) {
							reject(new Error('微信登录失败'))
						}
					})
					// #endif
				})
			},
			code2SessionWeixin: function() {
				return new Promise((resolve, reject) => {
					this.getWeixinCode().then((code) => {
						return uniCloud.callFunction({
							name: 'user-center',
							data: {
								action: 'code2SessionWeixin',
								params: {
									code,
								}
							}
						})
					}).then((res) => {
						resolve(res.result)
					}).catch((e) => {
						reject(e)
						uni.showModal({
							showCancel: false,
							content: '微信登录失败，请稍后再试'
						})
					})
				})
			}


			// 获取用户部门

		}
	}
</script>

<style>
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}

	.picker-view {
		width: 750rpx;
		height: 600rpx;
		margin-top: 20rpx;
	}

	.item {
		height: 50px;
		align-items: center;
		justify-content: center;
		text-align: center;
	}
</style>
